package dataS.headTailLinked;

//双端链表
public class HeadTailLinked {
    public Node head;
    public Node tail;

    public HeadTailLinked(){
        head=null;
        tail=null;
    }
    //从头部插入
    public void insertFromHead(int value){
        Node tmp=new Node(value);
        if(head==null){
            head=tmp;
        }else{
            tmp.next=head;
        }
        tail=tmp;
    }
    //从尾部插入
    public void insertFromTail(int value){
        Node tmp=new Node(value);
        if(tail==null){
            head=tmp;
        }else {
            tail.next=tmp;
        }
        tail=tmp;

}

    //从头部删除
    public void deleteFromHead(){
        if(head.next!=null){
            head=head.next;
        }else{
            head=null;
        }
    }

    //从尾部删除,该类中最复杂的方法
    public void deleteFromTail(){
        //找到尾节点的前一个节点
        Node tmp=head;
        while (tmp!=null){
            if(tmp.next!=null) {
                Node tmpnext = tmp.next;
                if(tmpnext==tail){
                   tmp.next=null;
                   tail=tmp;
                }
                tmp=tmp.next;
            }else {
                head=null;
                return;
            }
        }
    }


    //遍历节点
    public void display() {
        //创建一个临时节点
        Node tmp = head;
        while (tmp!= null){
            System.out.print(tmp.val + " ");
            tmp = tmp.next;
        }
        System.out.println();

    }
}
